package com.cg.servlet;

import com.cg.Student;
import com.cg.service.StudentService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/student/add")
public class AddStuServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String stuNo = req.getParameter("stuNo");
        String stuName = req.getParameter("stuName");
        int age = Integer.parseInt(req.getParameter("age"));
        String major = req.getParameter("major");
        //将获取到的参数封装为学生对象
        Student student = new Student();
        student.setStuName(stuName);
        student.setStuNo(stuNo);
        student.setMajor(major);
        student.setAge(age);
        //调用StudentService.add方法新增学生
        StudentService service = new StudentService();
        int result = service.add(student);
        String msg = "";
        if (result == 1) {
            //如果新增成功，则重定向到学生列表
            resp.sendRedirect(req.getContextPath() + "/student/list");
        } else {
            //如果新增失败，则给与用户详细的提示信息
            if (result == -1) {
                msg = "学生编号已存在";
            } else {
                msg = "新增学生失败";
            }
            req.setAttribute("msg", msg);
            req.getRequestDispatcher("/addStu.jsp").forward(req, resp);
        }
    }
}
